package controller

import (
	"fmt"
	"gin/CloudRestaurant/param"
	"gin/CloudRestaurant/service"
	"gin/CloudRestaurant/tool"
	"github.com/gin-gonic/gin"
)

type MemberController struct {

}

func (mc *MemberController)Router(engine *gin.RouterGroup)  {
	// 发送 短信 验证码
	engine.GET("/api/sendcode",mc.sendSmsCode)
	// 验证 短信 验证码
	engine.POST("api/login_sms",mc.smsLogin)
	// 发送 图像 验证码
	engine.GET("api/captcha",mc.captcha)
	//  验证验证码是否成功
	engine.POST("api/vertifycha",mc.vertifyCaptcha)
}

// 生成图像验证码
func (mc *MemberController) captcha(context *gin.Context) {
	// todo 生成验证码 并返回客户端
	tool.GenerateCaptcha(context)
}
// 验证验证码是否正确
func (mc *MemberController)vertifyCaptcha(context *gin.Context)  {
	var captcha tool.CaptchaResult
	err := tool.Decode(context.Request.Body,&captcha)
	if err != nil{

		tool.Failed(context,"参数解析失败")
		return
	}

	result := tool.VertifyCaptcha(captcha.Id,captcha.VertifyValue)
	if result{
		fmt.Println("验证通过")
	}else {
		fmt.Println("验证失败")
	}
}
// 填写验证码 验证验证码是否成功
// http://localhost:8090/api/sendcode?phone=111111
func (mc *MemberController) sendSmsCode(context *gin.Context) {
	// 发送验证码
	phone,exist := context.GetQuery("phone")
    if !exist {
    	tool.Failed(context,"参数解析失败")
		return
	}

	ms := service.MemberService{}
	isSend := ms.Sendcode(phone)
	if isSend{
		tool.Success(context,"发送验证码成功")
		return
	}
	tool.Success(context,"发送验证码失败")
	return
}
// 手机号——短信 登录方法
func (mc *MemberController)smsLogin(context *gin.Context)  {
	var smsLoginParam param.SmsLoginParam
	err := tool.Decode(context.Request.Body,&smsLoginParam)
	if err!= nil{
		fmt.Println(err)
		tool.Failed(context,"参数解析失败")
	}
	// 完成手机+验证码登录
	us := service.MemberService{}
	member := us.SmsLogin(smsLoginParam)
	if member!= nil{
		tool.Success(context,member)
		return
	}
	tool.Failed(context,"登录失败")
	return
}
